package com.uptown.mq.config;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;


/**
 * redis分布式锁
 */
@Service
public class DistributedLock {

	@Autowired
	private JedisFactory jedisFactory;

    private static final String LOCK_SUCCESS = "OK";

	private static final String DEFAULT_APPEND_TIME = "60";

	private static final Long RELEASE_SUCCESS = 1L;



    /**
     * 尝试获取分布式锁
     * @param lockKey 锁
     * @param expireTime 超期时间
     * @return 是否获取成功
     */
    public boolean setDistributedLock(String lockKey, int expireTime) {
		Jedis jedis = jedisFactory.getJedis();

		String result = jedis.setex(lockKey, expireTime, "1");
        if (LOCK_SUCCESS.equals(result)) {
            return true;
        }
        return false;
    }


    /**
     * 释放分布式锁
     * @param lockKey 锁
     * @return 是否释放成功
     */
    public boolean releaseDistributedLock(String lockKey) {
		Jedis jedis = jedisFactory.getJedis();

        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        Object result = jedis.eval(script, Collections.singletonList(lockKey), Collections.singletonList("1"));
        if (RELEASE_SUCCESS.equals(result)) {
            return true;
        }
        return false;
    }

	/**
	 * 重置时间
	 * @param lockKey
	 * @return
	 */
	public void expandLockTime(String lockKey) {
		Jedis jedis = jedisFactory.getJedis();

    	String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('expire', KEYS[1],ARGV[2]) else return '0' end;";

    	List<String> args2 = new ArrayList<>();
    	args2.add("1");
    	args2.add(DEFAULT_APPEND_TIME);
		jedis.eval(script, Collections.singletonList(lockKey), args2);
	}

}
